package org.jcnc.labreport.controller;

import org.jcnc.labreport.service.DashScopeService;
import org.jcnc.labreport.util.MarkdownConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * DashScope 控制器，提供与 DashScope API 交互的接口。
 */
@RestController
@RequestMapping("/api/dashscope")
public class DashScopeController {

    private final DashScopeService dashScopeService;
    private final ConcurrentHashMap<String, String> requestStatuses = new ConcurrentHashMap<>();

    @Autowired
    public DashScopeController(DashScopeService dashScopeService) {
        this.dashScopeService = dashScopeService;
    }

    /**
     * 单个请求接口，输入提示词，返回转换后的 HTML 静态页面。
     *
     * @param prompt 提示词
     * @param fileIds 文件 ID 列表（可选）
     * @return 异步返回的 HTML 内容
     */
    @GetMapping(value = "/request", produces = MediaType.TEXT_HTML_VALUE)
    public CompletableFuture<String> sendRequest(@RequestParam String prompt, @RequestParam(required = false) List<String> fileIds) {
        // 处理 fileIds，若为空则默认空列表
        fileIds = fileIds == null || fileIds.isEmpty() ? List.of("") : fileIds;

        // 更新请求状态为 "正在运行"
        requestStatuses.put(prompt, "正在运行");

        // 异步调用服务并在结果返回后将 Markdown 转换为 HTML
        return dashScopeService.sendRequestAsync(prompt, fileIds, requestStatuses)
                .thenApply(MarkdownConverter::convertToHtml);
    }
}
